package cn.com.support.dal;

import java.util.List;

import org.mybatis.spring.support.SqlSessionDaoSupport;

import cn.com.commons.Paginator;

/**
 * 默认的DAO
 * 
 * @since 2012-3-6 上午12:31:57
 * @version 1.0
 * @author Microbun
 */
public abstract class DefaultDAO<T extends BaseDO> extends SqlSessionDaoSupport
		implements BaseDAO<T> {

	/**
	 * SQL satement 包名
	 * 
	 * @return
	 */
	protected abstract String getSatementPackage();

	@Override
	public Integer deleteById(Long obj) throws DAOException {
		try {
			return getSqlSession()
					.delete(getSatementPackage() + ".deleteById", obj);
		} catch (Exception e) {
			throw new DAOException(e);
		}
	};

	@Override
	public Long insert(T obj) throws DAOException {
		try {
			return (long) getSqlSession().insert(
					getSatementPackage() + ".insert", obj);
		} catch (Exception e) {
			throw new DAOException(e);
		}
	}

	@Override
	public Integer updateById(T obj) throws DAOException {
		try {
			return getSqlSession()
					.update(getSatementPackage() + ".updateById", obj);
		} catch (Exception e) {
			throw new DAOException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <C> List<T> selectList(C query) throws DAOException {
		try {
			return getSqlSession().selectList(
					getSatementPackage() + ".selectList", query);
		} catch (Exception e) {
			throw new DAOException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public T selectById(Long id) throws DAOException {
		try {
			return (T) getSqlSession().selectOne(
					getSatementPackage() + ".selectById", id);
		} catch (Exception e) {
			throw new DAOException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <C> Paginator<C, List<T>> selectForPage(
			Paginator<C, List<T>> paginator) throws DAOException {
		try {
			// 先算出页面大小，以便获取页面偏移量
			int totalcount = (Integer) getSqlSession().selectOne(
					getSatementPackage() + ".selectForPageTotalCount",
					paginator);
			paginator.setTotalItems(totalcount);
			// 然后根据页面偏移可以查询当前页记录
			List<T> result = (getSqlSession().selectList(
					getSatementPackage() + ".selectForPage", paginator));
			paginator.setResult(result);
		} catch (Exception e) {
			throw new DAOException(e);
		}
		return paginator;
	}

}
